﻿using System;
using System.IO;
using System.Text;
using System.Web;
using System.Xml.Serialization;

namespace WebSite.Request
{
    public abstract class HttpHandlerBase : IHttpHandler
    {
        #region IHttpHandler 成员

        public bool IsReusable
        {
            get { return true; }
        }

        public abstract void ProcessRequest(HttpContext context);

        #endregion

        protected string ObjectToJSON(object obj)
        {
            //string jsonString;
            //JsonSerializerSettings setting = new JsonSerializerSettings();
            //setting.CheckAdditionalContent = false;
            //setting.NullValueHandling = NullValueHandling.Ignore;
            //setting.ObjectCreationHandling = ObjectCreationHandling.Reuse;
            //setting.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
            //setting.Formatting = Formatting.None;
            //setting.MissingMemberHandling = MissingMemberHandling.Ignore;
            //setting.PreserveReferencesHandling = PreserveReferencesHandling.All;
            //setting.StringEscapeHandling = StringEscapeHandling.Default;
            //jsonString = JsonConvert.SerializeObject(obj, Formatting.None, setting);
            try
            {
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                StringBuilder builder = new StringBuilder();
                StringWriter writer = new StringWriter(builder);

                serializer.Serialize(writer, obj);
                return builder.ToString();
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
            //return jsonString;
        }

        protected T JSONToObject<T>(string data)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            object obj = null;
            try
            {
                obj = serializer.Deserialize(new StringReader(data));
            }
            catch
            {
            }
            if (obj is T)
                return (T)obj;
            else
                return default(T);
        }
    }
}